<template>
  <div class="announcement-list">
    <a-card title="公告列表">
      <template #extra>
        <a-button type="primary" @click="$router.push('/announcements/create')">发布公告</a-button>
      </template>

      <a-table 
        :columns="columns" 
        :data-source="dataSource" 
        :loading="loading"
        bordered 
        :pagination="pagination"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'time'">
            {{ new Date(record.time).toLocaleString() }}
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a @click="handleView(record)">查看</a>
              <a style="color: #ff4d4f" @click="handleDelete(record)">删除</a>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { message, Modal } from 'ant-design-vue'
import { announcementAPI } from '@/api/announcement'
import type { Announcement } from '@/api/announcement'

const router = useRouter()
const loading = ref(false)
const dataSource = ref<Announcement[]>([])

const columns = [
  { title: 'ID', dataIndex: 'id', key: 'id', width: 80 },
  { title: '标题', dataIndex: 'title', key: 'title' },
  { title: '发布人', dataIndex: 'user_name', key: 'user_name', width: 120 },
  { title: '发布时间', dataIndex: 'time', key: 'time', width: 180 },
  { title: '操作', key: 'action', width: 150 }
]

const pagination = ref({
  total: 0,
  current: 1,
  pageSize: 10,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    pagination.value.current = page
    pagination.value.pageSize = pageSize
    loadData()
  }
})

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const res = await announcementAPI.getAnnouncementList({
      page: pagination.value.current,
      page_size: pagination.value.pageSize,
      ordering: '-time'
    })
    dataSource.value = res.data.results
    pagination.value.total = res.data.count
  } catch (error: any) {
    message.error('加载数据失败: ' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

// 查看详情
const handleView = (row: Announcement) => {
  router.push(`/announcements/detail/${row.id}`)
}

// 删除公告
const handleDelete = (row: Announcement) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除公告「${row.title}」吗？`,
    okText: '确定',
    cancelText: '取消',
    onOk: async () => {
      try {
        await announcementAPI.deleteAnnouncement(row.id)
        message.success('删除成功')
        loadData()
      } catch (error: any) {
        message.error('删除失败: ' + (error.response?.data?.message || error.message))
      }
    }
  })
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
</style>
